from sqlalchemy.orm import Session
from sqlalchemy import desc
from typing import List, Dict, Any
from db.mysql.official_contact import OfficialContact
from utils.result import Result


def create_contact(db: Session, name: str, phone: str, description: str = None) -> Result:

    try:
        contact = OfficialContact(
            name=name,
            phone=phone,
            description=description
        )
        db.add(contact)
        db.commit()
        db.refresh(contact)
        return Result.success(data=contact.to_dict(), msg="创建成功")
    except Exception as e:
        db.rollback()
        return Result.fail(msg=f"创建失败: {str(e)}")


def get_contact_list(db: Session, skip: int = 0, limit: int = 100) -> Result:

    try:
        contacts = db.query(OfficialContact).order_by(desc(OfficialContact.created_at)).offset(skip).limit(limit).all()
        total = db.query(OfficialContact).count()
        contacts_data = [contact.to_dict() for contact in contacts]
        return Result.success(
            data={
                "items": contacts_data,
                "total": total,
                "skip": skip,
                "limit": limit
            },
            msg="获取成功"
        )
    except Exception as e:
        return Result.fail(msg=f"获取失败: {str(e)}")


def get_contact_by_id(db: Session, contact_id: int) -> Result:

    try:
        contact = db.query(OfficialContact).filter(OfficialContact.id == contact_id).first()
        if contact:
            return Result.success(data=contact, msg="获取成功")
        else:
            return Result.fail(msg="未找到指定联系信息")
    except Exception as e:
        return Result.fail(msg=f"获取失败: {str(e)}")
